#region Header

// <file>
//     <copyright see="prj:///doc/copyright.txt"/>
//     <license see="prj:///doc/license.txt"/>
//     <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
//     <version>$Revision: 2683 $</version>
// </file>

#endregion Header

namespace ICSharpCode.TextEditor.Document
{
    using System;

    /// <summary>
    /// Description of TextAnchor.
    /// </summary>
    public sealed class TextAnchor
    {
        #region Fields

        int columnNumber;
        LineSegment lineSegment;

        #endregion Fields

        #region Constructors

        internal TextAnchor(LineSegment lineSegment, int columnNumber)
        {
            this.lineSegment = lineSegment;
            this.columnNumber = columnNumber;
        }

        #endregion Constructors

        #region Properties

        public int ColumnNumber
        {
            get {
                if (lineSegment == null) throw AnchorDeletedError();
                return columnNumber;
            }
            internal set {
                columnNumber = value;
            }
        }

        public bool IsDeleted
        {
            get {
                return lineSegment == null;
            }
        }

        public LineSegment Line
        {
            get {
                if (lineSegment == null) throw AnchorDeletedError();
                return lineSegment;
            }
            internal set {
                lineSegment = value;
            }
        }

        public int LineNumber
        {
            get {
                return this.Line.LineNumber;
            }
        }

        public TextLocation Location
        {
            get {
                return new TextLocation(this.ColumnNumber, this.LineNumber);
            }
        }

        public int Offset
        {
            get {
                return this.Line.Offset + columnNumber;
            }
        }

        #endregion Properties

        #region Methods

        public override string ToString()
        {
            if (this.IsDeleted)
                return "[TextAnchor (deleted)]";
            else
                return "[TextAnchor " + this.Location.ToString() + "]";
        }

        internal void Deleted()
        {
            lineSegment = null;
        }

        static Exception AnchorDeletedError()
        {
            return new InvalidOperationException("The text containing the anchor was deleted");
        }

        #endregion Methods
    }
}